<template>
  <div class="app-container">
	
	<el-dialog title="出库商品管理" @closed="baseClosed" v-model="baseOpen" width="90%" destroy-on-close append-to-body :close-on-click-modal="false">
	
	 <el-descriptions title="出库信息" size="small" border :column="4">
		<template #extra>
			<el-button v-if="outStore.status=='0'||outStore.status=='2'" type="success" @click="submitStatus"><el-icon><CircleCheckFilled /></el-icon>提交</el-button>
			<el-button v-if="outStore.status=='1'" type="primary" @click="handleAuditor"><el-icon><Checked /></el-icon>审批</el-button>
		</template>
		<el-descriptions-item label="ID">{{outStore.id}}</el-descriptions-item>
		<el-descriptions-item label="出库标题">{{outStore.title}}</el-descriptions-item>
		<el-descriptions-item label="出库类型">{{outStore.text.type}}</el-descriptions-item>
		<el-descriptions-item label="出库时间">{{outStore.outTime}}</el-descriptions-item>
		<el-descriptions-item label="出库人">{{outStore.outBy}}</el-descriptions-item>
		<el-descriptions-item label="出库原因">{{outStore.reason}}</el-descriptions-item>
		<el-descriptions-item v-if="outStore.status!='1'&&outStore.status!='0'" label="总进货金额">{{outStore.sumPurchase}}</el-descriptions-item>
		<el-descriptions-item v-if="outStore.status!='1'&&outStore.status!='0'" label="总销售金额">{{outStore.sumSale}}</el-descriptions-item>
		<el-descriptions-item v-if="outStore.status!='1'&&outStore.status!='0'" label="总数">{{outStore.total}}</el-descriptions-item>
		<el-descriptions-item label="审批状态">{{outStore.text.status}}</el-descriptions-item>
		<el-descriptions-item v-if="outStore.status!='1'&&outStore.status!='0'" label="审批人">{{outStore.auditorBy}}</el-descriptions-item>
		<el-descriptions-item v-if="outStore.status!='1'&&outStore.status!='0'" label="审批时间">{{outStore.auditorTime}}</el-descriptions-item>
		<el-descriptions-item v-if="outStore.status!='1'&&outStore.status!='0'" label="审批结果">{{outStore.rejectReason}}</el-descriptions-item>
		<el-descriptions-item label="备注">{{outStore.remark}}</el-descriptions-item>
	  </el-descriptions>

    <el-table v-loading="loading" :data="outGoodsList" @selection-change="handleSelectionChange"
	border
	:span-method="arraySpanMethod"
	size="small"
	style="height: calc(100vh - 380px);"
	>
      <el-table-column type="index" label="序号" width="55" fixed="left" align="center" />
	  <el-table-column label="商品概要" fixed="left">
		  <el-table-column label="名称|商品码" align="center" prop="goodsName" width="280" >
				<template #default="scope">
					<div v-if="scope.row.isAdd" style="text-align: left;">
						<selectGoods lable="输入搜索商品信息:" @selectChange="goodsQuerySelectChange"/>
					</div>
					<div v-else>
						<span>{{scope.row.goodsName}}</span>|<span>{{scope.row.goodsCode}}</span>
					</div>
				</template>
		  </el-table-column>
		  <el-table-column label="商品类型" sortable align="center" prop="goodsType" width="120">
		    <template #default="scope">
		      <dict-tag :options="bus_goods_type" :value="scope.row.goodsType"/>
		    </template>
		  </el-table-column>
	  </el-table-column>
	  <el-table-column label="出库信息">
		  <el-table-column label="出库数量" align="center" prop="outCount">
			  <template #default="scope">
					<el-input v-model="scope.row.outCount" :disabled="outStore.status==1||outStore.status==3" @input="(val)=>tableInputOutCount(val,scope.row)" @change="tableChangeOutCount(val,scope.row)" style="width: 90px" min="1" type="number"  placeholder="请输入出库量" />
			  </template>
		  </el-table-column>
		  <el-table-column label="原库存" align="center" prop="inventory" />
		  <el-table-column label="现库存" align="center" prop="currentInventory">
			 <template #default="scope">
				 <el-text v-if="scope.row.currentInventory>0" tag="b">{{scope.row.currentInventory}}</el-text>
				 <el-text v-if="scope.row.currentInventory==0" type="warning" tag="b">{{scope.row.currentInventory}}</el-text>
				 <el-text v-if="scope.row.currentInventory<0" type="danger" tag="b">{{scope.row.currentInventory}}</el-text>
			  </template>
		  </el-table-column>
		  <el-table-column label="总进货价" align="center" prop="sumPurchasePrice" />
		  <el-table-column label="总销售价" align="center" prop="sumSalePrice" />
	  </el-table-column>
	  <el-table-column label="商品信息">
		  <el-table-column label="进货价" align="center" prop="purchasePrice" />
		  <el-table-column label="销售价" align="center" prop="salePrice" />
		  <el-table-column label="货号" align="center" prop="goodsNo" />
		  <el-table-column label="规格" align="center" prop="norms" />
       </el-table-column>
          
      <el-table-column label="操作" v-if="outStore.status=='0'||outStore.status=='2'" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['crm:outGoods:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
	
	</el-dialog>
    

    <!-- 添加或修改出库商品对话框 -->
    <el-dialog :title="title" v-model="open" width="50%" append-to-body>
		
	 <el-table :data="tableData" stripe  border size="small" style="width: 100%;height: calc(100vh - 550px);">
		<el-table-column type="index" label="序号" width="55" fixed="left" align="center" />
		<el-table-column label="商品信息">
			<template #default="scope">
				【{{scope.row.text.goodsType}}】{{scope.row.goodsName}}||{{scope.row.goodsCode}}
			</template>
		</el-table-column>
		<el-table-column label="库存信息">
			<template #default="scope">
				商品现库存：<el-text type="success" tag="b">{{scope.row.goodsInventory}}</el-text>
				扣减：<el-text type="warning" tag="b">{{scope.row.outCount}}</el-text>
				审批通过后剩余：<el-text type="danger" tag="b">{{scope.row.goodsInventory-scope.row.outCount}}</el-text>
			</template>
		</el-table-column>
	  </el-table>
		<el-divider content-position="left">审批信息</el-divider>
      <el-form ref="outGoodsRef" :model="form" :rules="rules" label-width="80px">
		  <el-form-item label="审批状态" prop="status">
		   <el-select v-model="form.status" placeholder="请选择审批状态">
				<el-option label="通过" value="3" />
				<el-option label="未通过" value="2" />
		   </el-select>
		  </el-form-item>
        <el-form-item label="审批结果" prop="rejectReason" style="width: 70%;">
          <el-input v-model="form.rejectReason" maxlength="200" type="textarea" placeholder="请输入审批结果" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">提交审批</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="OutGoods">
import { listOutGoods, getOutGoods, delOutGoods, addOutGoods, updateOutGoods,listComparison } from "@/api/crm/outGoods";
import { getOutStore,submitAuditor,doAuditor} from "@/api/crm/outStore";
import selectGoods from '../goods/select.vue';
import { watch } from "vue";

const { proxy } = getCurrentInstance();

const { bus_goods_type } = proxy.useDict('bus_goods_type');

const baseOpen = ref(false);

const outGoodsList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("出库商品审批");

const tableData = ref([]);


const outStore = ref(null)

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 1000,
    storeId: null,
    goodsId: null,
    goodsName: null,
    goodsCode: null,
    goodsType: null,
    goodsNo: null,
    norms: null,
    outCount: null,
    inventory: null,
    currentInventory: null,
    purchasePrice: null,
    salePrice: null,
    sumPurchasePrice: null,
    sumSalePrice: null,
  },
  rules: {
	   status: [
	       {required: true,message: '请选择商品状态',trigger: 'change'},
	    ],
		rejectReason:[
			 { required: true, message: '请输入审批结果', trigger: 'blur' }
		]
  },
  defaultItem:{
  	  isAdd:true,
	  id:null,
  	  storeId: null,
  	  goodsId: null,
  	  goodsName: null,
  	  goodsCode: null,
  	  goodsType: null,
  	  goodsNo: null,
  	  norms: null,
  	  outCount: null,
  	  inventory: null,
  	  currentInventory: null,
  	  purchasePrice: null,
  	  salePrice: null,
  	  sumPurchasePrice: null,
  	  sumSalePrice: null,
  	  remark: null,
  	  createBy: null,
  	  createTime: null,
  	  updateBy: null,
  	  updateTime: null
  }
});

const { queryParams, form, rules,defaultItem } = toRefs(data);

const emit = defineEmits(['closed'])


/** 查询出库商品列表 */
function getList() {
	
	queryParams.value.storeId = outStore.value.id
	
  loading.value = true;
  listOutGoods(queryParams.value).then(response => {
    outGoodsList.value = response.rows;
    total.value = response.total;
    loading.value = false;
	
	if(outStore.value.status=='0'||outStore.value.status=='2'){
		outGoodsList.value.push(defaultItem.value)
	}
  });
}


function openWin(id){
	getOutStore(id).then(rsp=>{
		outStore.value = rsp.data;
		baseOpen.value = true;
		
		
		getList();
	})
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    status:null,
	rejectReason:null
  };
  proxy.resetForm("outGoodsRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加出库商品";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getOutGoods(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改出库商品";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["outGoodsRef"].validate(valid => {
    if (valid) {
		form.value.id = outStore.value.id;
		
		let _tip = '确定退回审批信息吗？';
		if(form.value.status=='3'){
			_tip = '确定审批通过并同步库存信息吗？';
		}
		
		proxy.$modal.confirm(_tip).then(function() {
		  return doAuditor(form.value);
		}).then(() => {
		  proxy.$modal.msgSuccess("审批提交成功");
		  
		  open.value = false;
		  baseOpen.value = false;
		}).catch(() => {});
		
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除出库商品编号为"' + _ids + '"的数据项？').then(function() {
    return delOutGoods(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('crm/outGoods/export', {
    ...queryParams.value
  }, `outGoods_${new Date().getTime()}.xlsx`)
}

function arraySpanMethod(params){
	
	if(true==params.row.isAdd){
		//debugger
		if(params.columnIndex==1){
			return [1, 7]
		}
		return [0,0]
	}
	return [1,1]
}

function goodsQuerySelectChange(item){
	//检测是否已添加
	for (var i = 0; i < outGoodsList.value.length; i++) {
		if(outGoodsList.value[i].goodsId==item.id){
			outGoodsList.value[i].outCount ++;
			return;
		}
	}
	
	const tempItem = builderStordGoodModel(item,1);
	
	addOutGoods(tempItem).then(rsp=>{
		outGoodsList.value.splice(outGoodsList.value.length-1,0,rsp.data);
	});
	
}

function builderStordGoodModel(gd,outCount){
	return {
		storeId: outStore.value.id,
		goodsId: gd.id,
		goodsName: gd.goodsName,
		goodsCode: gd.goodsCode,
		goodsType: gd.goodsType,
		goodsNo: gd.goodsNo,
		norms: gd.norms,
		outCount: outCount,
		inventory: gd.inventory,
		currentInventory: gd.inventory-outCount,  //原库存减1
		purchasePrice: gd.purchasePrice,
		salePrice: gd.salePrice,
		sumPurchasePrice: gd.purchasePrice*outCount,
		sumSalePrice: gd.salePrice*outCount,
		remark: null
	}
}


function tableInputOutCount(val,row){
	val = parseInt(val);
	
	if(val<=0){
		val= 1;
		row.outCount = val;
	}
	
	row.currentInventory = row.inventory-val;
	row.sumPurchasePrice = row.purchasePrice*val;
	row.sumSalePrice = row.salePrice*val;
}

function tableChangeOutCount(val,row){
	var submitData = {'id':row.id,'outCount':row.outCount}
	updateOutGoods(submitData).then(rsp=>{
	})
}


/**
 * 提交状态
 */
function submitStatus(){
	var count = 0;
	for (var i = 0; i < outGoodsList.value.length; i++) {
		if(!outGoodsList.value[i].isAdd){
			count++;
		}
	}
	if(count==0){
		proxy.$modal.msg("请添加出库商品.");
		return;
	}
	
	proxy.$modal.confirm('确定要提交当前商品出库审批吗？').then(function() {
		return submitAuditor(outStore.value.id);
	}).then(() => {
		baseOpen.value = false;
		proxy.$modal.msgSuccess("提交成功");
	}).catch(() => {});
}


function handleAuditor(){
	listComparison(outStore.value.id).then(rsp=>{
		tableData.value = rsp.data;
		open.value = true;
	})
}


function baseClosed(){
	 emit('closed')
}


defineExpose({
	openWin
})

</script>
